<template>
  <div class="login">
    <Form ref="formInline" :model="formInline" :rules="ruleInline" inline>
      <FormItem prop="username">
        <Input type="text" v-model="formInline.username" placeholder="Username">
          <Icon type="ios-person-outline" slot="prepend"></Icon>
        </Input>
      </FormItem>
      <FormItem prop="password">
        <Input type="password" v-model="formInline.password" placeholder="Password">
          <Icon type="ios-lock-outline" slot="prepend"></Icon>
        </Input>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="handleSubmit('formInline')">登录</Button>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="back">返回</Button>
      </FormItem>
    </Form>
    <div id="result">
      {{result}}
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data: function (){
    return{
      formInline: {
        username: '',
        password: ''
      },
      ruleInline: {
        user: [
          { required: true, message: 'Please fill in the password.',trigger: 'blur' }
        ],
        password: [
          { required: true, message: 'Please fill in the password.', trigger: 'blur' },
          // { type: 'string', min: 4, trigger: 'blur' }
        ]
      },
      token: "",
      result: "",
    }
  },
  methods:{
    handleSubmit:function (){
        let obj1 = {
          "username": this.formInline.username,
          "password": this.formInline.password,
        }
        if(this.formInline.password.length < 4){
          this.result = "密码长度不可小于4位"
          return;
        }
        this.$axios.post("http://localhost:8090/user/login",obj1)
        .then(res => {
            if(res.data.code == 200){
              this.token = res.data.result.token; //获得token
              this.result = "登录成功"
              //对localStorage进行操作
              console.log("localStorage success")
              localStorage.setItem("token", this.token)
              localStorage.setItem("username", this.formInline.username)
              console.log(localStorage.getItem("token"))
              console.log(localStorage.getItem("username"))
              this.$router.push({
                  path: '/home',
                  params: {
                    username: this.formInline.username,
                  }
              })
            }else{
              this.result = "登录失败,用户名或密码不正确!"
            }
        })
    },
    back:function (){
      this.$router.go(-1)
    }
  },
  created() {
  },
}
</script>

<style scoped>
  #result{
    color: red;
  }
</style>